<template>
  <div>
    <el-form :model="dataForm" ref="dataForm" label-width="100px" size="small" :rules="rules">
      <el-form-item label="海报名称:" prop="styleName">
        <el-input v-model="dataForm.styleName" placeholder="不超过15个字" maxlength="15" clearable></el-input>
      </el-form-item>
      <el-form-item label="选择产品:" prop="productType">
        <el-select placeholder="请选择产品类型" clearable filterable v-model="dataForm.productType" style="width:100%">
          <el-option v-for="(value, key) in dicts['product_type'].childMap" :key="key" :label="value" :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item label="推广渠道:" prop="channelCode">
        <el-select placeholder="请选择推广渠道" clearable filterable v-model="dataForm.channelCode" style="width:100%">
          <el-option v-for="(value, key) in dicts['recommend_style_channel'].childMap" :key="key" :label="value" :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item label="海报图片:" prop="imgBase64"></el-form-item>
      <el-form-item label-width="0" prop="imgBase64">
        <el-upload class="poster-uploader" :file-list="fileList" action="" drag :limit="1" :show-file-list="true" :on-change="changeImg" :on-remove="removeImg" :auto-upload="false">
          <div class="img-container" v-if="!tempImage">
            <i class="el-icon-upload"></i>
          </div>
          <div class="el-upload__text" v-if="!tempImage">点击或拖动文件上传</div>
          <div class="el-upload__tip" style="color: #999;" v-if="!tempImage">仅支持上传一个文件，支持格式：.jpg .png，单个文件最大不超过5M</div>
          <img :src="tempImage" alt="" v-if="tempImage" style="height: 100%;width:auto;"/>
        </el-upload>
      </el-form-item>
      <el-form-item style="margin-top: 10px" label-width="130px">
        <el-button type="" @click="closeEvent">
          取消
        </el-button>
        <el-button type="primary" @click="submit">
          <fa-icon class="fa-check" />{{buttonName}}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { CONSTANT_OBJ } from '@/utils/constant'
import { common } from '@/utils/common'
import api from '../api'
export default {
  props: { editData: Object },
  data () {
    return {
      dataForm: {
        recommendStyleId: '',
        styleName: '',
        productType: '',
        channelCode: '',
        styleType: 'MANAGER',
        imgBase64: null
      },
      buttonName: '新增并生效',
      tempImage: '',
      fileList: [],
      rules: {
        styleName: [{ required: true, message: '请输入海报名称', trigger: 'blur' }],
        productType: [{ required: true, message: '请选择产品类型', trigger: 'blur' }],
        channelCode: [{ required: true, message: '请选择推广渠道', trigger: 'blur' }],
        imgBase64: [{ required: true, message: '请上传海报图片', trigger: 'blur' }]
      }
    }
  },
  mounted () {
    if (this.editData && this.editData.recommendStyleId) {
      common.listAssign(this.dataForm, this.editData)
      this.tempImage = this.editData.styleImg
      // this.imageToBase64(this.editData.styleImg, (res) => {
      //   console.log('base64', res)
      //   this.dataForm.imgBase64 = res
      // })
      this.rules.imgBase64[0].required = false
      this.buttonName = '编辑并更新'
    }
    console.log(this.dataForm)
    console.log(this.editData)
  },
  methods: {
    // 校验海报图片是否符合规格
    changeImg (file) {
      const isJPGorPNG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
      const isLt5M = file.raw.size / 1024 / 1024 < 5
      if (!isJPGorPNG) {
        this.$message.error('上传海报图片支持.jpg和.png格式')
      }
      if (!isLt5M) {
        this.$message.error('上传海报图片大小不能超过5MB!')
      }
      if (isJPGorPNG && isLt5M) {
        this.file2Base64(file.raw)
      }
      return isJPGorPNG && isLt5M
    },
    // file转base64
    file2Base64 (file) {
      const _this = this
      const fileReader = new FileReader()
      fileReader.readAsDataURL(file)
      fileReader.onload = function (e) {
        _this.dataForm.imgBase64 = e.target.result
        _this.tempImage = e.target.result
      }
    },
    imageToBase64 (url, callback) {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      let img = new Image()
      img.src = url + `?t=${Math.random()}`
      img.src = url
      img.setAttribute('crossOrigin', 'Anonymous')
      img.onload = function () {
        canvas.width = img.width
        canvas.height = img.height
        ctx.drawImage(img, 0, 0)
        console.log(img, '图片名称')
        if (url.indexOf('/') > 0) {
          let imageType = url.substring(url.lastIndexOf('/') + 1, url.length)
          let type = imageType.split('?')[0].split('.')[1]
          console.log(type, '图片名称')
          let base64 = canvas.toDataURL(`image/${type}`)
          callback(base64)
        }
      }
    },
    // 移除图片
    removeImg (file) {
      this.dataForm.imgBase64 = null
      this.tempImage = ''
    },
    /**
     * 提交
     */
    submit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.dataForm, '提交参数')
          if (this.editData && this.editData.recommendStyleId) {
            this.editUser()
          } else {
            this.addUser()
          }
        }
      })
    },
    // 新增
    addUser () {
      api.postAdd(this.dataForm).then(res => {
        const { responseCode, responseMsg } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.$message({
            message: `${responseMsg}`,
            type: 'success'
          })
          this.rules.imgBase64[0].required = true
          this.$emit('updateSuccess')
        }
      })
    },
    // 编辑
    editUser () {
      api.putEdit(this.dataForm).then(res => {
        const { responseCode, responseMsg } = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.$message({
            message: `${responseMsg}`,
            type: 'success'
          })
          this.rules.imgBase64[0].required = true
          this.$emit('updateSuccess')
        }
      })
    },
    closeEvent () {
      this.rules.imgBase64[0].required = true
      this.$emit('close')
    }
  },
  computed: {
    ...mapState({
      dicts: state => state.common.dicts
    })
  }
}
</script>

<style scoped>
.poster-uploader {
  width: 100%;
}
.poster-uploader >>> .el-upload {
  display: block;
}
.poster-uploader >>> .el-upload-dragger {
  width: 100%;
}

</style>
